package fr.inria.arles.temperatureManagement.tempSensor;


import com.sun.spot.sensorboard.EDemoBoard;
import com.sun.spot.io.j2me.radiogram.*;
import com.sun.spot.sensorboard.peripheral.ILightSensor;
import com.sun.spot.sensorboard.peripheral.ITemperatureInput;
import com.sun.spot.sensorboard.peripheral.ITriColorLED;
import com.sun.spot.util.Utils;
import javax.microedition.io.*;
import javax.microedition.midlet.MIDlet;
import javax.microedition.midlet.MIDletStateChangeException;

/**
 * MIDIlet running on sensor and sampling the temperature.
 *
 * @author ajay chhatwal
 */
public class TempSensorSampler extends MIDlet {

    private static final int HOST_PORT = 67;
    private static final int SAMPLE_PERIOD = 10 * 1000;  // in milliseconds

    protected void startApp() throws MIDletStateChangeException {
        RadiogramConnection rCon = null;
        Datagram dg = null;
        ITemperatureInput tempSensor = EDemoBoard.getInstance().
                getADCTemperature();
        ILightSensor lightSensor = EDemoBoard.getInstance().getLightSensor();
        ITriColorLED[] leds = EDemoBoard.getInstance().getLEDs();
        double temp = 0;

        new com.sun.spot.util.BootloaderListener().start();
        // Listen for downloads/commands over USB connection
        try {
            // Open up a broadcast connection to the host port
            // where the 'on Desktop' portion of this demo is listening
            rCon = (RadiogramConnection) Connector.open("radiogram://broadcast:"
                    + HOST_PORT);
            dg = rCon.newDatagram(10);
            long now = 0L;

            while (true) {
                int light=lightSensor.getValue();
                temp = (light*50)/1024;

                // Flash an LED to indicate a sampling event
                leds[7].setRGB(255, 255, 255);
                leds[7].setOn();

                // Package the time and sensor reading into a radio datagram and
                // send it.
                dg.reset();
                dg.writeDouble(temp);
                rCon.send(dg);

                System.out.println("Temp. value = " + temp);

                leds[7].setOff();
                now = System.currentTimeMillis();
                // Go to sleep to conserve battery
                Utils.sleep(SAMPLE_PERIOD - (System.currentTimeMillis() - now));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

   /**
     * This will never be called by the Squawk VM
     */
    protected void pauseApp() {

    }

    /**
     * Only called if startApp throws any exception other than
     * MIDletStateChangeException.
     *
     * @throws MIDletStateChangeException
     */
    protected void destroyApp(boolean arg0) throws MIDletStateChangeException {

    }
}
